package cn.idongjia.task.excuter.dispacher;

import cn.idongjia.task.common.exception.TaskException;
import cn.idongjia.task.common.task.*;
import com.lts.core.domain.Action;
import com.lts.core.domain.Job;
import com.lts.tasktracker.Result;
import com.lts.tasktracker.runner.JobContext;
import com.lts.tasktracker.runner.JobRunner;
import org.apache.commons.cli.MissingArgumentException;
import org.apache.log4j.Logger;

/**
 * Created by renxianlong on 16/4/8.
 */
public class TaskDispacher implements JobRunner{

    private Logger logger = Logger.getLogger(TaskDispacher.class);

    @Override
    public Result run(JobContext jobContext) throws Throwable {

        Task task = JobToTask.convert(jobContext.getJob());
        Result result = new Result(Action.EXECUTE_SUCCESS,"success");

        try {
            String taskType = task.getTaskType();
            TaskRunner taskRunner = TaskRunnerManager.getInstance().getTaskRunner(taskType);
            if(null == taskRunner){
                logger.debug("根据taskType"+taskType+"没有找到对应的taskRunner");
                return result;
            }
            ExcuteResult excuteResult = taskRunner.run(task);
            if(cn.idongjia.task.common.task.Result.EXECUTE_FAILED.equals(excuteResult.getResult())){
                if(FaultType.RETRY.equals(task.getFaultType())){
                    logger.debug("任务执行失败,稍后重试");
                    result.setAction(Action.EXECUTE_LATER);
                }
                result.setAction(Action.EXECUTE_FAILED);
                result.setMsg(excuteResult.getMsg());
            }
        }catch (TaskException e ){
            //业务侧主动抛出异常,不重试
            logger.error(e.getStackTrace());
            result.setAction(Action.EXECUTE_EXCEPTION);
            result.setMsg(e.getMsg());
        }catch (RuntimeException e){
            //业务侧主动抛出异常,不重试
            logger.error(e.getStackTrace());
            result.setAction(Action.EXECUTE_EXCEPTION);
            result.setMsg(e.getMessage());
        }
        return result;
    }
}
